import React, { useMemo, useState } from 'react';
import { Dropdown, message } from 'antd';
import { GlobalHeaderContext } from '@/components/GlobalHeader/GlobalHeaderStore';
import styles from '../../styles.less';
import MyIcon from '@/components/MyIcon';
import SwitchPosition from '@/components/GlobalHeader/components/PersonalSettings/components/SwitchPosition';
import SwitchTheme from '@/components/GlobalHeader/components/PersonalSettings/components/SwitchTheme';
import { useRequest } from '@@/plugin-request/request';
import { logoutRequest } from '@/services/BaseLayout';
import { getPosIDs, getSysteState, getTenantID, getTheme, getUserID, logout } from '@/utils';
import { history } from 'umi';
import { addLayoutService, editLayoutService } from './services';
import { ReloadLayoutModal } from './components';
import avatar from '../../../../../public/image/userAvatar.png';
// 'https://gw.alipayobjects.com/zos/rmsportal/BiazfanxmamNRoxxVxka.png';
const index: React.FC<any> = (props) => {
  let switchPosRef = React.useRef<any>(null);

  const { allUserInfo, positionList, switchingPos, dispatch, settings, setLayoutSettings, BasicLayoutProps, permissions, baseLogin } =
    React.useContext(GlobalHeaderContext);

  /**
   * 获取布局数据
   */
  const { welcomeLayout } = baseLogin;

  const [visibleTheme, setVisibleTheme] = useState(false);

  const [visibleSwitch, setVisibleSwitch] = useState(false);

  /**
   * 是否打开 重置布局 modal
   */
  const [showReloadLayout, setShowReloadLayout] = useState<boolean>(false);

  const userLogOut = useRequest(
    () => {
      return logoutRequest();
    },
    {
      manual: true,
    },
  );

  /**
   * 获取布局详情数据
   */
  const targetLayout = useMemo(() => {
    let nowLayoutInfo: any = baseLogin?.userInfo?.muserLayoutList?.find((i: any) => {
      return i?.layoutType === `${getTenantID()}10011001` && i?.userPositionID == getPosIDs();
    });
    return nowLayoutInfo;
  }, [allUserInfo, baseLogin?.userInfo]);

  /**
   * 新增编辑后的接口回调
   * @param res
   */
  const layoutCallback = (res: any) => {
    if (res && res?.msgFlag) {
      message.success(res?.msg);
      dispatch({
        type: 'baseLogin/changeWelocmeLayout',
        payload: {
          openWelcomeLayout: {
            isDraggable: false,
            isResizable: false,
            monitorLayout: true,
            layoutLoading: false,
          },
        },
      });
    } else {
      dispatch({
        type: 'baseLogin/changeWelocmeLayout',
        payload: {
          openWelcomeLayout: {
            isDraggable: false,
            isResizable: false,
            monitorLayout: true,
            layoutLoading: false,
          },
        },
      });
      message.error(res?.msg);
    }
  };

  /**
   * 引入新增布局接口
   */
  const { addLayoutRun } = addLayoutService(layoutCallback);

  /**
   * 引入编辑布局接口
   */
  const { editLayoutRun } = editLayoutService(layoutCallback);

  /**
   * 菜单点击方法
   * @param key
   */
  const onMenuClick = (key: string) => {
    //切换岗位
    if (key === 'switchPosition') {
      onOpenSwitch(); //打开岗位弹窗
    }

    //切换主题
    if (key === 'switchTheme') {
      onOpenTheme();
    }

    //退出登录
    if (key === 'logout') {
      onLogoutClick();
    }

    /**
     * 个人中心
     */
    if (key == 'personalCenter') {
      history.push({
        pathname: '/commonController/reloadSelfInfo',
      });
    }

    /**
     * 任务中心
     */
    if (key == 'taskCenter') {
      history.push({
        pathname: '/commonController/manager',
      });
    }
    /**
     * 开启首页布局
     */
    if (key == 'openLayout') {
      dispatch({
        type: 'baseLogin/changeWelocmeLayout',
        payload: {
          openWelcomeLayout: {
            isDraggable: true,
            isResizable: true,
            monitorLayout: false,
            layoutLoading: false,
          },
        },
      });
    }

    /**
     * 关闭首页布局
     */
    if (key == 'closeLayout') {
      dispatch({
        type: 'baseLogin/changeWelocmeLayout',
        payload: {
          openWelcomeLayout: {
            isDraggable: false,
            isResizable: false,
            monitorLayout: false,
            layoutLoading: true,
          },
        },
      });
      onSaveLayout();
    }

    /**
     * 重置首页布局
     */
    if (key == 'reloadLayout') {
      setShowReloadLayout(true);
    }

    /**
     * 版本信息
     */
    if (key == 'versionIteration') {
      history.push({
        pathname: '/versionController/getVersionTypeList',
      });
    }
  };

  /**
   * 关闭时候 保存布局
   */
  const onSaveLayout = () => {
    if (targetLayout) {
      editLayoutRun({
        userID: getUserID(),
        layoutType: getTenantID() + '10011001',
        routeURL: '/workmanage/workbench',
        layoutInfo: welcomeLayout,
        versionNum: targetLayout?.versionNum,
        id: targetLayout?.id,
        userPositionID: getPosIDs(),
      });
    } else {
      addLayoutRun({
        userID: getUserID(),
        layoutType: getTenantID() + '10011001',
        routeURL: '/workmanage/workbench',
        layoutInfo: welcomeLayout,
        userPositionID: getPosIDs(),
      });
    }
  };

  /* 关闭主题抽屉 */
  const onCloseTheme = () => {
    setVisibleTheme(false);
  };

  /* 打开主题抽屉 */
  const onOpenTheme = () => {
    setVisibleTheme(true);
  };

  /* 关闭切换岗位 */
  const onCloseSwitch = () => {
    setVisibleSwitch(false);
  };

  /* 打开切换岗位 */
  const onOpenSwitch = () => {
    setVisibleSwitch(true);
  };

  /*退出操作*/
  const onLogoutClick = async () => {
    try {
      await userLogOut.run();
      await logout('hrky');
    } catch (e) {}
  };

  // 下拉菜单 V4.24.8 写法
  const items = useMemo(() => {
    const iconStyle: React.CSSProperties = {
      marginRight: '.5rem',
    };
    let newMenuList: any = [];
    let menuItems: any = [
      {
        label: (
          <span
            onClick={() => {
              onMenuClick('switchPosition');
            }}
          >
            <MyIcon type="icon-qiehuan" style={iconStyle} />
            切换岗位
          </span>
        ),
        key: 'switchPosition',
        disabled: false,
      },
      {
        label: (
          <span
            onClick={() => {
              onMenuClick('switchTheme');
            }}
          >
            <MyIcon type="layout" style={iconStyle} />
            主题切换
          </span>
        ),
        key: 'switchTheme',
        disabled: false,
      },
      // {
      //   label: (
      //     <span
      //       onClick={() => {
      //         onMenuClick('personalCenter');
      //       }}
      //     >
      //       <MyIcon type="icon-user" style={iconStyle} />
      //       个人中心
      //     </span>
      //   ),
      //   key: 'personalCenter',
      //   disabled: permissions?.['/commonController/modifyPwd'] ? false : true,
      // },
      // {
      //   label: (
      //     <span
      //       onClick={() => {
      //         onMenuClick('taskCenter');
      //       }}
      //     >
      //       <MyIcon type="icon-user" style={iconStyle} />
      //       任务中心
      //     </span>
      //   ),
      //   key: 'taskCenter',
      //   disabled: permissions?.['/commonController/modifyPwd'] ? false : true,
      // },

      // 暂时不启用
      // {
      //   label: (
      //     <span
      //       onClick={() => {
      //         onMenuClick('openLayout');
      //       }}
      //     >
      //       <MyIcon type="icon-buju_daohanglan" style={iconStyle} />
      //       开启布局
      //     </span>
      //   ),
      //   key: 'openLayout',
      //   disabled: !baseLogin?.openWelcomeLayout?.isDraggable ? false : true,
      // },
      // {
      //   label: (
      //     <span
      //       onClick={() => {
      //         onMenuClick('closeLayout');
      //       }}
      //     >
      //       <MyIcon type="buju_daohanglan" style={iconStyle} />
      //       关闭布局
      //     </span>
      //   ),
      //   key: 'closeLayout',
      //   disabled: baseLogin?.openWelcomeLayout?.isDraggable ? false : true,
      // },
      // {
      //   label: (
      //     <span
      //       onClick={() => {
      //         onMenuClick('reloadLayout');
      //       }}
      //     >
      //       <MyIcon type="icon-retweet" style={iconStyle} />
      //       重置布局
      //     </span>
      //   ),
      //   key: 'reloadLayout',
      //   disabled: targetLayout && targetLayout?.id ? false : true,
      // },
      // {
      //   label: (
      //     <span
      //       onClick={() => {
      //         onMenuClick('versionIteration');
      //       }}
      //     >
      //       <MyIcon type="icon-version" style={iconStyle} />
      //       版本信息
      //     </span>
      //   ),
      //   key: 'versionIteration',
      //   disabled: permissions?.['/versionController/manage'] ? false : true,
      // },
      {
        type: 'divider', // 菜单分割线
      },
      {
        label: (
          <span
            onClick={() => {
              onMenuClick('logout');
            }}
          >
            <MyIcon type="icon-logout" style={iconStyle} />
            退出登录
          </span>
        ),
        key: 'logout',
        disabled: false,
      },
    ];
    newMenuList = menuItems?.filter((item: any) => {
      return !item?.disabled;
    });

    if (getSysteState() == 'OA') {
      newMenuList = newMenuList?.filter((item: any) => {
        return item?.key != 'logout' && item?.type != 'divider';
      });
    }

    return newMenuList;
  }, [baseLogin?.openWelcomeLayout, permissions, welcomeLayout]);

  /** 判断 */
  const hrkyTheme = () => {
    if (getTheme() == 'd2844c70-3adf-4a7e-9320-2b7f6fdec5b1') {
      return true;
    } else {
      return false;
    }
  };

  return (
    <>
      <Dropdown menu={{ items }} placement="bottomLeft" className={hrkyTheme() ? 'proLayoutMenuHeadBg' : ''}>
        <div className={styles['header-dropDown-layout']}>
          <img src={allUserInfo?.imageUrl ?? avatar} className={styles['avatar-size']} />
          <span className={styles['user-name']} style={{ color: BasicLayoutProps?.layout === 'top' ? '#ffffff' : '' }}>
            {allUserInfo?.realName}
          </span>
        </div>
      </Dropdown>

      {/* 岗位弹窗  */}
      {visibleSwitch && (
        <SwitchPosition
          positionList={positionList}
          switchingPos={switchingPos}
          allUserInfo={allUserInfo}
          dispatch={dispatch}
          ref={switchPosRef}
          onClose={onCloseSwitch}
        />
      )}

      {/* 重置布局  */}
      {showReloadLayout && (
        <ReloadLayoutModal
          open={showReloadLayout}
          onClose={() => {
            setShowReloadLayout(false);
          }}
        />
      )}

      {/*主题切换Drawer*/}
      <SwitchTheme visible={visibleTheme} onClose={onCloseTheme} settings={settings} setLayoutSettings={setLayoutSettings} />
    </>
  );
};

export default index;
